package com.example.leetcode.leetcode.hot100;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

/**
 * @author haitao
 * @date 2022/6/9 3:08 下午
 * 寻找两个正序数组的中位数字
 * log(m+n)
 * 思路：1.先排序再求中位数
 * 2.
 */
public class Solution4 {


    public double findMedianSortedArrays(int[] nums1, int[] nums2) {



        int length = nums1.length + nums2.length;
        // 计算中位数的位置
        int mid = length / 2;
        if (nums1.length ==0&& nums2.length>0){
            return singleNum(nums2);
        }
        if (nums2.length ==0&& nums1.length>0){
            return singleNum(nums1);
        }
//        int lowLength = nums1.length> nums2.length ?  ;
//        if (){
//
//        }


        int point1 = 0, point2 = 0;

        while (point1 < nums1.length - 1 && point2 < nums2.length - 1 && point1 + point2 < mid) {
            if (nums1[point1] > nums2[point2]) {
                point2++;
            } else if (nums1[point1] <= nums2[point2]) {
                point1++;
            }
        }

        if (length % 2 != 0) {
            return nums1[point1] > nums2[point2] ? (double) nums1[point1] : (double) nums2[point2];
        }

        return (double) (nums1[point1] + nums2[point2]) / 2;
    }


    public double singleNum(int[] nums) {
        int mid = nums.length / 2;
        if (nums.length % 2 == 0) {
            return (double) (nums[mid] + nums[mid + 1]) / 2;
        } else {
            return nums[mid];
        }
    }

    public static void main(String[] args) {
        Solution4 solution4 = new Solution4();
        int[] nums1 = {1,2};
        int[] nums2 = {5,6,7,8};
        System.out.println(solution4.findMedianSortedArrays(nums1, nums2));

    }

}
